//------------------------------------------------------------------------------
//  <copyright file="InterpolationAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Threading;

    /// <summary>
    /// Agent that performs a interpolation.
    /// It subscribes to two producers and lists received messages until it can perform interpolation of input messages for the timer message.
    /// This is a separate class with its own port so that it can match up messages without blocking. If the message processing is slower, it won't affect the 
    /// matching up. The alternative would be to have this functionality in the InterpolationConsumerProducerAgent directly, in which case message would get dropped
    /// if the processing was slow.
    /// </summary>
    /// <remarks>
    /// Ideally this class would derive twice from ISubscriptionReceiver. 
    /// Unfortunately managed code has an unintuitive restriction on inheriting multiple times from the same generic interface, 
    /// because it can create ambiguity when TInput1 is the same as TInput2. This restriction goes away if a class is used instead (ConsumerProducerAgent in this case). 
    /// </remarks>
    /// <typeparam name="TInput">The first type of input messages accepted by the agent.</typeparam>
    /// <typeparam name="TTimer">The second type of input messages accepted by the agent.</typeparam>
    internal sealed class InterpolationAgent<TInput, TTimer> :
        ConsumerProducerAgent<TInput, InterpolationMessage<TInput>>,
        ISubscriptionReceiver<TTimer>
        where TInput : AgentMessage
        where TTimer : AgentMessage
    {
        /// <summary>
        /// The maximum number of messages that can accumulate in a list before we consider it a bug.
        /// </summary>
        private const int DefaultMaxListSize = 1000;

        /// <summary>
        /// The additional producer agent we subscribe to.
        /// </summary>
        private readonly string producerAgentName2;

        /// <summary>
        /// A list that stores the messages received on the first (input) port.
        /// The messages are removed from the list when they are no longer need for interpolation (a newer message with OriginatingTime 
        /// less than the lowest timestamp on messageList2.)
        /// </summary>
        private List<TInput> inputList;

        /// <summary>
        /// The oldest message in the list.
        /// </summary>
        private TInput oldestInput;

        /// <summary>
        /// A list that stores the originating times of messages received on the second (timer) port.
        /// The originating times are removed from the list when they are matched or are proven to be match-less.
        /// </summary>
        private List<long> timerList;       

        /// <summary>
        /// The agent we subscribe to.
        /// </summary>
        private IAgentHost producerAgent2;

        /// <summary>
        /// Initializes a new instance of the <see cref="InterpolationAgent{TInput, TTimer}" /> class.
        /// </summary>
        /// <param name="name">The name of the agent.</param>
        /// <param name="producerAgentName1">The name of the first producer to subscribe to.</param>
        /// <param name="producerAgentName2">The name of the second producer to subscribe to.</param>
        public InterpolationAgent(string name, string producerAgentName1, string producerAgentName2)
            : base(name, producerAgentName1)
        {
            this.producerAgentName2 = producerAgentName2;
            this.inputList = new List<TInput>();
            this.timerList = new List<long>();
        }

        /// <summary>
        /// Called after construction, to allow the agent to finish initialization. 
        /// </summary>
        /// <param name="locator">A locator that can be used to find other agents.</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            this.producerAgent2 = locator.GetAgent(this.producerAgentName2);
            this.producerAgent2.Subscribe<TTimer>(this);
        }

        /// <summary>
        /// Called when the agent transitions from inactive to active.
        /// </summary>
        public override void OnActivated()
        {
            this.producerAgent2.Activate();
            base.OnActivated();
        }

        /// <summary>
        /// Called when the agent transitions from active to inactive.
        /// </summary>
        public override void OnDeactivated()
        {
            this.producerAgent2.Deactivate();
            base.OnDeactivated();
            this.oldestInput = null;
            this.inputList.Clear();
            this.timerList.Clear();
        }

        /// <summary>
        /// Called when a new input message is available. 
        /// </summary>
        /// <param name="input">The new message to receive.</param>
        /// <remarks>
        /// Since the message processing is very short and the intent is to inspect all messages that come in in search of start and end bracketing, 
        /// this method is marked as blocking (meaning a publisher is blocked if publishing faster than this agent can sustain, which realistically happens only if our thread doesn't get any proc time).
        /// Note that the publisher is still async, and is only blocked if the interpolation agent is running 2 messages behind 
        /// (interpolation agent is processing one, the receiver has another one and the publisher is trying to publish a third one).
        /// </remarks>
        [ReceiverConfiguration(BlockIfFull = true)]
        public override void Receive(TInput input)
        {         
            this.ValidateOrder(input, this.inputList);
            this.inputList.Add(input);

            this.Interpolate();
        }

        /// <summary>
        /// Called when a new input message is available.
        /// </summary>
        /// <param name="timer">The new message to receive.</param>
        /// <remarks>See the remarks on the other Receive method for why this is marked as blocking.</remarks>
        [ReceiverConfiguration(BlockIfFull = true)]
        public void Receive(TTimer timer)
        {
            if (this.timerList.Count > 0)
            {
                this.ValidateOrder(timer.OriginatingTime, this.timerList[this.timerList.Count - 1]);
            }

            this.timerList.Add(timer.OriginatingTime);
            this.Interpolate();
        }

        /// <summary>
        /// Interpolate input based on timer.
        /// </summary>
        private void Interpolate()
        {
            // Is this message older than the oldest message in the timer list? If so, we have something to publish (or throw away from timer list)
            while (this.timerList.Count > 0 && this.inputList.Count > 0 && this.inputList[this.inputList.Count - 1].OriginatingTime > this.timerList[0])
            {
                long timerOriginatingTime = this.timerList[0];
                this.timerList.Remove(timerOriginatingTime);
                while (this.inputList.Count > 0 && this.inputList[0].OriginatingTime <= timerOriginatingTime)
                {
                    this.oldestInput = this.inputList[0];
                    this.inputList.Remove(this.oldestInput);
                }

                // If we have a start message to bracket the timer message, publish it. Otherwise discard it.
                // The discarding happens only initially when the timer message may have timestamps before the input message.
                if (this.oldestInput != null && this.oldestInput.OriginatingTime <= timerOriginatingTime)
                {                    
                    this.Publisher.Post(new InterpolationMessage<TInput>(this.oldestInput, this.inputList[0], timerOriginatingTime));
                }
            }
        }

        /// <summary>
        /// Ensures that the message is older than the contents of the list.
        /// </summary>
        /// <typeparam name="T1">The type of messages in the list</typeparam>
        /// <param name="message">The new message</param>
        /// <param name="list">The existing list of messages</param>
        private void ValidateOrder<T1>(T1 message, List<T1> list) where T1 : AgentMessage
        {
            // assert that messages are ordered
            if (list.Count > 0)
            {
                T1 previousMessage = list[list.Count - 1];
                if (previousMessage != null)
                {
                    this.ValidateOrder(message.OriginatingTime, previousMessage.OriginatingTime);
                }
            }
        }

        /// <summary>
        /// Ensures that the message is older than the previous message.
        /// </summary>        
        /// <param name="originatingTime">The new message originating time</param>
        /// <param name="previousMessageOriginatingTime">The previous message originating time</param>
        private void ValidateOrder(long originatingTime, long previousMessageOriginatingTime)
        {
            // assert that messages are ordered           
            if (previousMessageOriginatingTime > originatingTime)
            {
                throw new Exception(string.Format("Invalid message ordering. Got {0} after {1}", originatingTime, previousMessageOriginatingTime));
            }          
        }
    }
}
